<template>
  <span class="animated-number">
    {{ prefix }}{{ displayValue }}{{ suffix }}
  </span>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { gsap } from 'gsap'
import type { AnimatedNumberProps } from '@/types'

const props = withDefaults(defineProps<AnimatedNumberProps>(), {
  duration: 1000,
  prefix: '',
  suffix: ''
})

const displayValue = ref('0')

function animateValue() {
  const obj = { value: 0 }
  
  gsap.to(obj, {
    value: props.value,
    duration: props.duration / 1000,
    ease: 'power2.out',
    onUpdate: () => {
      const formatted = props.format 
        ? props.format(obj.value)
        : Math.round(obj.value).toString()
      displayValue.value = formatted
    }
  })
}

watch(() => props.value, () => {
  animateValue()
})

onMounted(() => {
  animateValue()
})
</script>

<style lang="scss" scoped>
.animated-number {
  font-variant-numeric: tabular-nums;
}
</style>
